import logging
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session
# from sqlalchemy.sql.functions import user
from info import constants
from info import redis_store
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu

@index_blu.route('/new_list')
def new_list():
    cid=request.args.get('cid','1')
    page=request.args.get('page','1')
    per_page=request.args.get('per_page','10')
    try:
        cid=int(cid)
        page=int(page)
        per_page=int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    filter=[]
    if cid !=1:
        try:
            filter.append(News.category_id==cid)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    try:
        paginate=News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    news_list=[]
    for news in paginate.items:
        news_list.append(news.to_dict())
    data={
        "total_page":paginate.pages,
        "current_page":paginate.page,
        "news_list":news_list
    }
    return jsonify(errno=RET.OK,data=data)

@index_blu.route('/')
@user_login_data
def index():
    # session['name']='itheima'
    # logging.debug("This is a debug log.")
    # logging.info("This is a info log.")
    # logging.warning("This is a warning log.")
    # logging.error("This is a error log.")
    # logging.critical("This is a critical log.")
    # redis_store.set("age","18")
    news_list=[]

    try:
        news_list=News.query.order_by(News.clicks.desc()).limit(constants.HOME_PAGE_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list=[]
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())
    try:
        categories=Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    cate_li=[]
    for cate in categories:
        cate_li.append(cate.to_dict())
    user=g.user
    data={
        "user":user.to_dict() if user else None,
        "news_dict_list":news_dict_list,
        "cate_li":cate_li
    }

    return render_template('news/index.html',
                           data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
    # return index_blu.send_static_file('news/favicon.ico')


@index_blu.route('/login',methods=['GET','POST'])
def login():
    pass